package com.tian.controller.interceptor;

import com.tian.utils.JSONResult;
import com.tian.utils.JsonUtils;
import com.tian.utils.RedisOperator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;

public class UserTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisOperator redisOperator;
    public static final String REDIS_USER_TOKEN ="redis_user_token";



    /**
     * 拦截请求，在访问controller调用之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

  //      System.out.println("进入到拦截器，被拦截...");

        String userId = request.getHeader("headerUserId");
        String userToken = request.getHeader("headerUserToken");
        System.out.println(userId);
        System.out.println(userToken);

        if (StringUtils.isNotBlank(userId)&&StringUtils.isNotBlank(userToken)){
            String uniqueToken = redisOperator.get(REDIS_USER_TOKEN + ":" + userId);
            //可能用户修改了信息，导致userid变了，导致uniqueToken为空
            if (StringUtils.isBlank(uniqueToken)){
            //    System.out.println("请登录。。。");
                returnErrorResponse(response,JSONResult.errorMsg("请登录.."));
                return false;
            }else {
                if (!uniqueToken.equals(userToken)){
                //    System.out.println("账号在异地登录");
                    returnErrorResponse(response,JSONResult.errorMsg("账号在异地登录"));
                    return false;
                }
            }
        }else {
         //   System.out.println("请登录...");
            returnErrorResponse(response,JSONResult.errorMsg("请登录.."));
            return false;
        }


        /**
         * false:请求被拦截，被驳回，验证出现问题
         * true:请求在经过验证校验以后，是OK的，是可以放行的
         */
        return true;
    }

    public void returnErrorResponse(HttpServletResponse response, JSONResult result){

        OutputStream out=null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("test/json");
            out=response.getOutputStream();
            out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 请求访问controller之后，渲染视图之前
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 请求访问controller之后，渲染视图之后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
